package com.example.hetong_system.controller;

import com.example.hetong_system.service.PaymentAndMilestoneService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付与里程碑计划接口（供前端调用）
 */
@RestController
@RequestMapping("/auth/payment")
public class PaymentController {

    @Autowired
    private PaymentAndMilestoneService paymentAndMilestoneService;

    private static final Logger logger = LoggerFactory.getLogger(PaymentController.class);

    /**
     * 前端点击支付后调用：自动创建payment_plan和milestone_plan
     * 接口路径：POST /auth/payment/create-plan
     * 入参：合同ID、支付金额、支付类型
     */
    @PostMapping("/create-plan")
    public ResponseEntity<Map<String, Object>> createPlan(
            @RequestParam("contractId") Long contractId,
            @RequestParam("amount") BigDecimal amount,
            @RequestParam("type") String type) { // type: deposit（定金）/ execution（执行款）

        Map<String, Object> result = new HashMap<>();
        try {
            // 调用Service创建记录，返回新创建的payment_plan的ID
            Long paymentPlanId = paymentAndMilestoneService.createPaymentAndMilestonePlan(contractId, amount, type);

            // 成功响应（给前端返回paymentPlanId，用于后续发起支付）
            result.put("success", true);
            result.put("message", "payment_plan和milestone_plan创建成功");
            result.put("data", paymentPlanId); // 核心返回值：新创建的付款计划ID
            return ResponseEntity.ok(result);
        } catch (IllegalArgumentException e) {
            // 已知异常（如合同不存在）
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            // 未知异常
            logger.error("创建payment_plan和milestone_plan失败", e);
            result.put("success", false);
            result.put("message", "创建失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}